import React, { useState } from 'react'
import { Stock } from '@antv/g2plot'
import _tt from '../../utils/tools'

export default function KLine(state: any) {
  let { addEcharsData: Function } = state
  var [data, setData] = useState<any[]>([
    {
      ts_code: Math.round(Math.random() * 999),
      trade_date: '2020-03-13',
      close: Math.round(Math.random() * 99),
      open: Math.round(Math.random() * 99),
      high: Math.round(Math.random() * 99),
      low: Math.round(Math.random() * 99),
      vol: Math.round(Math.random() * 99),
      amount: Math.round(Math.random() * 999),
    },
  ])
  var stockPlot: Stock

  function initEchars() {
    stockPlot = new Stock('container', {
      data,
      xField: 'trade_date',
      yField: ['open', 'close', 'high', 'low'],
      meta: {
        vol: { alias: '成交量' },
        open: { alias: '开盘价' },
        close: { alias: '收盘价' },
        high: { alias: '最高价' },
        low: { alias: '最低价' },
      },
      animation: {
        // 配置图表第一次加载时的入场动画
        appear: {
          animation: 'path-in', // 动画效果
          duration: 5000,  // 动画执行时间
        },
      }
    })

    stockPlot.render()
  }

  window.onload = () => {
    initEchars()
    addEcharsData()
  }

  const addEcharsData = () => {
    let time = setInterval(() => {
      let a = {
        ts_code: Math.round(Math.random() * 999),
        trade_date: _tt.parseTime(Math.round(Math.random() * 9999999999999)),
        close: Math.round(Math.random() * 99),
        open: Math.round(Math.random() * 99),
        high: Math.round(Math.random() * 99),
        low: Math.round(Math.random() * 99),
        vol: Math.round(Math.random() * 99),
        amount: Math.round(Math.random() * 999),
      }
      data.push(a)
      stockPlot.changeData(data)
      stockPlot.render()
      if (data.length > 10) {
        clearInterval(time)
      }
    }, 2000)
  }
  //  addEcharsData()
  return (
    <>
      <div id="container" />
    </>
  )
}
